package com.runa.monitor.platinterface.netservice.connect;

import com.runa.monitor.platinterface.netservice.connect.commstatus.CommStatus;
import com.runa.monitor.platinterface.netservice.equipment.PlcService;
import com.runa.protocol.dto.IRequestData;
import com.runa.protocol.dto.IResponseData;

import java.util.List;

/**
 * @author zhuj
 */
public class GeneralRequest implements IRequest<IRequestData> {

    private List<IRequest<IRequestData>> collective;

    private IResponse<IResponseData> response;

    private IRequestData requestData;

    private volatile boolean ready = false;

    private PlcService service;

    public GeneralRequest(IRequestData requestData, PlcService service) {
        this.service = service;
        this.requestData = requestData;
        response = new GeneralResponse(this);
    }

    @Override
    public IRequestData getRequestData() {
        return requestData;
    }

    @Override
    public IResponse getResponse() {
        return response;
    }

    @Override
    public boolean beReady() {
        return ready;
    }

    @Override
    public void reset() {
        ready = false;
    }

    public void setReady(boolean ready) {
        this.ready = ready;
        if (requestData.isReadWrite()) {
            service.handlerReadData(this);
        } else {
            service.handlerWriteData(this);
        }
    }

    @Override
    public void cancel(CommStatus status) {
        if (requestData.isReadWrite()) {
            service.resetReadRequest(this, status);
        } else {
            service.resetWriteRequest(status);
        }
    }

    @Override
    public boolean check() {
        return requestData.check(response.getResponseData());
    }

    private int[] flag;

    @Override
    public int flag(int pos) {
        return flag[pos];
    }

    @Override
    public void flag(int ...flag) {
        this.flag = flag;
    }

    @Override
    public void collective(List<IRequest<IRequestData>> collective) {
        this.collective = collective;
    }

    @Override
    public List<IRequest<IRequestData>> collective() {
        return collective;
    }
}
